<!-- 通用页面---监听器设置页面 -->
<template>
  <a-form :label-col="{ span: 4 }"
  :wrapper-col="{ span: 20 }">
      <a-form-item label="侦听器名称">
        <a-input  v-model:value="listeners.eventName"/>
      </a-form-item>
      <a-form-item label="事件类型">
        <a-select v-model:value="listeners.eventType" placeholder="" :options="listenerEventTypeOptions" />
      </a-form-item>
      <a-form-item label="执行动作">
        <a-select v-model:value="listeners.eventWay" placeholder="" :options="listenerTypeOptions" />
      </a-form-item>
      <a-form-item v-if="listeners.eventWay!=='temporaryVariable'" label="执行业务">
        <a-select v-model:value="listeners.eventDoc" placeholder="" :options="methodList" />
      </a-form-item>
      <a-form-item v-if="listeners.eventWay=='temporaryVariable'" label="传值设置">
        <div  style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
          <div style="overflow: auto;" class="tagboxs">
            <a-tag>
              传值设置
            </a-tag>
          </div>
          <a-button style="margin-left: auto;" size="small" secondary type="info" @click="openModal">
            <template #icon>
              <a-icon><svg-icon name="touxiang" size="18" /></a-icon>
            </template>请选择
          </a-button>      
        </div>
      </a-form-item>
    </a-form>
  
</template>

<script lang="tsx">
  import {
    defineComponent,
    withDefaults,
    defineProps,
    unref,
    markRaw,
    ref,
    computed,
    nextTick,
    onMounted,
    ComputedRef,
    defineExpose,
    reactive,
    watch
  } from 'vue';
  import { FormInst, FormRules, DataTableColumns, NButton } from 'naive-ui';
  import modeler from '@/store/modules/modeler';
  import { ModdleElement } from 'bpmn-moddle';
  import { Element } from 'diagram-js/lib/model/Types';
  
  import { getScriptType } from '@/components/design/bo-utils/scriptUtil';
  import EventEmitter from '@/components/design/utils/EventEmitter';
  import {listenerEventTypeOptions} from '@/components/design/components/DesignerCommCore/PanelOptions'
  import { useI18n } from '@/hooks/useI18n';
  import { businessMethods } from '@/store/modules/businessMethod';
  import ListenerSetting from '@/components/design/components//Panel/components/SubChild/ListenerSetting.vue';
  import { useModal } from '@/hooks/useModal/useModal';
  import type { SelectProps } from 'ant-design-vue';

  interface Props {
    defaultData?: {
      //defaultSelectData: any;
    };
  }
  const props = {
    defaultData:{
    }
  }
  export default defineComponent({
    name: 'ElementExecutionListeners',
    props,
    setup(props) {
      const { t } = useI18n();
      const modelerStore = modeler();
      const getActive = computed(() => modelerStore.getActive!);
      const getActiveId = computed<string>(() => modelerStore.getActiveId!);
      let listenersRaw = markRaw([]);
      let activeIndex = -1;
      const businessMethodStore = businessMethods();     
      let allMethods = businessMethodStore.getAllMethods();
      console.log(allMethods);
      const methodList = ref<SelectProps['options']>([  ]);
      allMethods.forEach((item)=>{
        methodList.value?.push({label:item.methodName,value:item.id});
      })    

      const modelVisible = ref(false);
      const listeners = ref<object>({eventName:'',eventType:'',eventWay:'',eventDoc:'',temporaryVariable:[],targetId:getActiveId.value});
      //const newListener = ref<ExecutionListenerForm>({ event: '', type: 'class' });
      const newListener = ref<ExecutionListenerForm>({ event: '', type: 'class' });
      const formRef = ref<FormInst | null>(null);
      const formItemVisible = ref<FormItemVisible>({
        listenerType: 'class',
        scriptType: 'none',
      });
      // const listenerEventTypeOptions = ref<Record<string, string>[]>([
      //   { label: '通用操作事件', value: 'commonEvent' },
      //   { label: '起草人操作人事件', value: 'startEvent' },
      //   { label: '起草人撤回事件', value: 'starterRejectEvent' },
      //   { label: '起草人废弃事件', value: 'starterDiscardEvent' },
      //   { label: '起草人催办事件', value: 'starterReminderEvent' },
      //   { label: '节点进入事件', value: 'nodeInitEvent' },
      //   { label: '节点结束事件', value: 'nodeEndEvent' },
      //   { label: '节点激活事件', value: 'nodeStartEvent' },
      //   // { label: '节点暂停事件', value: 'nodeStopEvent' },
      //   { label: '节点废弃事件', value: 'nodeReminderEvent' },
      //   { label: '节点处理人解析前拦截事件', value: 'nodeUserBeforeEvent' },
      //   // { label: '节点唤醒操作事件', value: 'nodeWakeUpEvent' },
      //   { label: '节点初始化事件', value: 'nodeLoadEvent' },
      //   { label: '处理人驳回事件', value: 'rejectEvent' },
      //   { label: '处理人通过事件', value: 'approveEvent' },
      //   { label: '处理人转办事件', value: 'transferEvent' },
      //   { label: '处理人补签事件', value: 'signedEvent' },
      //   { label: '已处理人撤回审批事件', value: 'recallEvent' },
      //   { label: '已处理人催办事件', value: 'reminderEvent' },
      //   // { label: '系统操作事件', value: 'systemOperationEvent' },
      //   // { label: '特权人终审通过事件', value: 'privilegedPassEvent' },
      //   // { label: '特权人消息销毁事件', value: 'privilegedDestructionEvent' },
      //   // { label: '特权人操作事件', value: 'privilegedOperationEvent' },
      //   // { label: '特权人异常重试事件', value: 'privilegedExceptionEvent' },
      //   // { label: '特权人废弃事件', value: 'privilegedReminderEvent' },
      //   // { label: '特权人前后跳转事件', value: 'privilegedJumpEvent' },
      //   // { label: '特权人修改流程事件', value: 'privilegedChangeFlowEvent' },
      //   // { label: '特权人修改当前处理人事件', value: 'privilegedChangeUsersEvent' },
      //   { label: '流程通用催办事件', value: 'flowReminderEvent' },
      //   // { label: '流程暂停事件', value: 'stopEvent' },
      //   // { label: '流程唤醒操作事件', value: 'wakeUpEvent' },
      //   // { label: '操作执行前事件', value: 'beforeActionEvent' }, 
      // ]);
      const listenerTypeOptions = ref<Record<string, string>[]>([
        { label: '业务方法', value: 'businessMethod' },
        { label: '流程业务扩展', value: 'extendMethod' },
        { label: '临时变量赋值', value: 'temporaryVariable' },
        // { label: '广播流程信号', value: 'script' },
      ]);
      const [ModalRender, modalRef] = useModal();
      const editFormRef = ref<any>(null);
      const editDrawerBindValue = reactive({
        defaultSelectData: []
      });
      const openModal = async () => {
        editDrawerBindValue.defaultSelectData = [];
        ModalRender.show({
          title: `传值设置`,
          width: '50%',
          destroyOnClose: true,
          content: () => {
            return <ListenerSetting  ref={editFormRef} defaultData={unref(editDrawerBindValue)}></ListenerSetting>;
          },
          // 确定方法执行
          onOk: async (values) => {
            //调用子页面的方法
            const res = await editFormRef.value?.handleSubmit();
            listeners.value.temporaryVariable=res.value;
            //if (!res) return;

        },
      });
    };
      // const listenerEventTypeOptions = ref<Record<string, string>[]>([
      //   { label: 'Start', value: 'start' },
      //   { label: 'End', value: 'end' },
      //   { label: 'Take', value: 'take' },
      // ]);
      // const listenerTypeOptions = ref<Record<string, string>[]>([
      //   { label: 'Java Class', value: 'class' },
      //   { label: 'Expression', value: 'expression' },
      //   { label: 'DelegateExpression', value: 'delegateExpression' },
      //   { label: 'Script', value: 'script' },
      // ]);
      // const scriptTypeOptions = ref<Record<string, string>[]>([
      //   { label: 'External Resource', value: 'external' },
      //   { label: 'Inline Script', value: 'inline' },
      //   { label: 'None', value: 'none' },
      // ]);
      const formRules: FormRules = {
        event: { required: true, trigger: ['blur', 'change'], message: '事件类型不能为空' },
        type: { required: true, trigger: ['blur', 'change'], message: '监听器类型不能为空' },
      };
   

      const updateListenerType = (value: string) => {
        formItemVisible.value.listenerType = value;
        newListener.value = {
          ...newListener.value,
          type: value,
          ...(value === 'script' ? { script: newListener.value.script || {} } : {}),
        };
      };
      const updateScriptType = (value: string) => {
        formItemVisible.value.scriptType = value;
        newListener.value.script = {
          scriptFormat: newListener.value.script?.scriptFormat,
          scriptType: value,
        };
      };

      
      const openListenerModel = async (index: number, listenerData?: ExecutionListenerForm) => {
        activeIndex = index;
        console.log(JSON.stringify(listenerData));
        listenerData && (newListener.value = JSON.parse(JSON.stringify(listenerData)));
        updateListenerType(listenerData?.type || 'class');
        modelVisible.value = true;
        await nextTick();
        formRef.value && formRef.value.restoreValidation();
      };
      const getListeners=()=>{
        const listenerData = listeners.value;
  
        const matchedOption = listenerEventTypeOptions.find(
          obj => obj.value === listenerData.eventType
        );
        const result = {
          ...listenerData, 
          eventTypeName: matchedOption ? matchedOption.label : ""
        };
  
        console.log(result, '处理后的监听器数据');
        return result;
      }
      // defineExpose({
      //   handleSubmit: getListeners,
      // });
      watch(()=>props,()=>{
        console.log(props,'props')
      },{
        deep:true,
        immediate:true
      })
      onMounted(() => {
        if(props.defaultData.defaultSelectData!=null){
          listeners.value=props.defaultData.defaultSelectData;
        }
        //console.log(props,"props11111111111111")
        //reloadExtensionListeners();
        //EventEmitter.on('element-update', reloadExtensionListeners);
      });

      return {
        modelVisible,
        getActiveId,
        getActive,
        formRef,
        listeners,
        newListener,
        formRules,
        openModal,
        //columns,
        formItemVisible,
        listenerEventTypeOptions,
        listenerTypeOptions,
        methodList,
        // scriptTypeOptions,
        // removeListener,
        getListeners,
        //saveExecutionListener,
        openListenerModel,
        updateListenerType,
        updateScriptType,
      };
    },
  });
</script>
